import 'package:enterprise_v6_app/app/components/toast_widget.dart';
import 'package:enterprise_v6_app/app/core/http/http.dart';
import 'package:enterprise_v6_app/app/core/utils/custom_event_bus.dart';
import 'package:enterprise_v6_app/app/core/utils/interface.dart';
import 'package:enterprise_v6_app/app/data/entities/application/education/couser_center/get_text_book_setting_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/education/couser_center/list_by_book_id_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/education/couser_center/list_question_by_book_id_entity.dart';
import 'package:enterprise_v6_app/app/modules/application/education/course_center/integrated_theme/course_detail_detail_page/course_detail_detail_page_controller.dart';
import 'package:enterprise_v6_app/app/modules/application/education/quiz/model.dart';
import 'package:enterprise_v6_app/router/app_pages.dart';
import 'package:get/get.dart';

///人脸识别后的课程详情 目录
class TrainDirectoryDetailController extends GetxController {
  ///根据课程查询目录列表
  List<ListByBookIdEntity>? listByBookIdEntity = [];

  ///用户点击后上一个视频ListByBookIdEntity对象
  ListByBookIdEntity? topListByBookIdEntity;

  ///根据课程查询试题列表
  List<ListQuestionByBookIdEntity>? listQuestionByBookIdEntity = [];

  ///查询课程设置
  GetTextBookSettingEntity? getTextBookSettingEntity;
  String planId = '';

  @override
  void onInit() {
    super.onInit();
    if (Get.arguments['planId'] != null) {
      planId = Get.arguments['planId'] as String;
    }

    //根据课程查询目录列表
    listByBookId();
    //查询课程设置(考试时长)
    getTextBookSetting();
    //根据课程查询试题列表
    listQuestionByBookId();
  }

  ///根据课程查询目录列表
  void listByBookId() async {
    final res = await HttpUtil().generateGetRequest<List<ListByBookIdEntity>>(
      Interface.listByBookId,
      queryParameters: {
        'bookId': Get.arguments['id'],
      },
    ).execute();
    res.onSuccess((result) {
      if (result.data != null) {
        listByBookIdEntity = result.data!;
        for (var directoryFile in listByBookIdEntity!) {
          if (Get.arguments['idDirectoryFile'] != null) {
            //directoryFile有可能一样 判断idDirectoryFile
            if (directoryFile.id == Get.arguments['idDirectoryFile'] as String) {
              //设置选中
              directoryFile.click = true;
              //设置上一个对象
              topListByBookIdEntity=directoryFile;
              //是否发送 并播放
              CustomEventBus.getInstance().fire(MyEntity(MyEntity.TYPEDIRECTORYFILE, '${Interface.fileUrl}${directoryFile.directoryFile}'));
              CustomEventBus.getInstance().fire(MyEntity(MyEntity.DEADLINE, directoryFile.deadline ?? 0));
              CustomEventBus.getInstance().fire(MyEntity(MyEntity.TYPEDIRECTORYFILEID, '${directoryFile.id}'));
            }
          }
        }
        update();
      }
    });
  }

  ///根据课程查询目录列表 目录--》选中状态修改
  void listByBookIdTwo(String? idDirectoryFile) async {
    final res = await HttpUtil().generateGetRequest<List<ListByBookIdEntity>>(
      Interface.listByBookId,
      queryParameters: {
        'bookId': Get.arguments['id'],
      },
    ).execute();
    res.onSuccess((result) {
      if (result.data != null) {
        listByBookIdEntity = result.data!;
        //这里 Get.arguments['directoryFile'] as String; 根据这个判断是否设置选中
        for (var directoryFile in listByBookIdEntity!) {
          if (idDirectoryFile != null) {
            //directoryFile有可能一样 判断idDirectoryFile
            if (directoryFile.id == idDirectoryFile) {
              //设置选中
              directoryFile.click = true;
            }
          }
        }
        update();
      }
    });
  }

  ///根据课程查询试题列表
  void listQuestionByBookId() async {
    final res = await HttpUtil().generateGetRequest<List<ListQuestionByBookIdEntity>>(
      Interface.listQuestionByBookId,
      queryParameters: {
        'id': Get.arguments['id'],
      },
    ).execute();
    res.onSuccess((result) {
      if (result.data != null) {
        listQuestionByBookIdEntity = result.data!;
        update();
      }
    });
  }


  //开始做题
  void startDoingQuestions() {
    final List<QuizTopic> topicsX = [];
    for (var listEntity in listQuestionByBookIdEntity!) {
      List<int>? answersX = [];
      final List<String> optionsX = [];
      if (listEntity.optionA != null) {
        optionsX.add('${listEntity.optionA}');
      }
      if (listEntity.optionB != null) {
        optionsX.add('${listEntity.optionB}');
      }
      if (listEntity.optionC != null) {
        optionsX.add('${listEntity.optionC}');
      }
      if (listEntity.optionD != null) {
        optionsX.add('${listEntity.optionD}');
      }
      //转码-对应的65 得到0的角标 A(65)-65=0
      answersX = listEntity.questionValidity?.split(';').map((e) => e.codeUnitAt(0) - 65).toList();
      topicsX.add(QuizTopic(
        id: listEntity.id ?? '',
        question: '${listEntity.questionMain}',
        answers: answersX,
        options: optionsX,
        score: listEntity.score ?? 0,
      ));
    }
    if (topicsX.isEmpty) {
      AppToast.showWarning('没有题目~');
      return;
    }
    Get.toNamed(AppRoutes.quizPage,
        arguments: QuizConfig(
          textbookId: Get.arguments['id'] as String,
          planId: planId,
          type: QuizType.lessonTest,
          topics: topicsX,
          leftSeconds: getTextBookSettingEntity?.duration != null ? getTextBookSettingEntity!.duration! * 60 : 60,
        ));
    //视频暂停
    Get.find<CourseDetailDetailPageController>().videoKey.currentState?.pause();
  }

  //练习记录
  void practiceRecords() {
    Get.toNamed(AppRoutes.quizHistoryPage, arguments: Get.arguments['id']);
    //视频暂停
    Get.find<CourseDetailDetailPageController>().videoKey.currentState?.pause();
  }

  //查询课程设置(考试时长)
  void getTextBookSetting() async {
    final res = await HttpUtil().generateGetRequest<GetTextBookSettingEntity>(
      Interface.getTextBookSetting,
      queryParameters: {
        'textbookId': Get.arguments['id'],
      },
    ).execute();
    res.onSuccess((result) {
      if (result.data != null) {
        getTextBookSettingEntity = result.data!;
      }
    });
  }

  ///新增课程观看记录
  void addCourseWatchRecord(int? totalDurationInSeconds, int? currentPositionDurationInSeconds, String? directoryFileId, String? directoryFileIdCurrent) async {
    final res = await HttpUtil().generatePostRequest(Interface.addCourseWatchRecord, data: {
      'textbookId': Get.arguments['id'], //	课程id
      'totalDuration': totalDurationInSeconds, //总时长
      'deadline': currentPositionDurationInSeconds, //截至时间(观看进度)
      'directoryId': directoryFileId, //课程目录id（下个界面发过来的）
      'planId': planId, //计划id (上上个界面传入)
    }).execute();
    res.onSuccess((result) {
      //当前需要id 判断id是否选中
      listByBookIdTwo(directoryFileIdCurrent);
    });
  }

  void addCourseWatchRecordK(int? totalDurationInSeconds, int? currentPositionDurationInSeconds,  String? directoryFileIdCurrent) async {
    final res = await HttpUtil().generatePostRequest(Interface.addCourseWatchRecord, data: {
      'textbookId': Get.arguments['id'], //	课程id
      'totalDuration': totalDurationInSeconds, //总时长
      'deadline': currentPositionDurationInSeconds, //截至时间(观看进度)
      'directoryId': directoryFileIdCurrent, //课程目录id（当前id）
      'planId': planId, //计划id (上上个界面传入)
    }).execute();
    res.onSuccess((result) {
      //当前需要id 判断id是否选中
      listByBookIdTwo(directoryFileIdCurrent);
      //刷新上个界面
      CustomEventBus.getInstance().fire(MyEntity(MyEntity.TYPEPAGEREFASH, ''));

    });
  }
}
